#include "CTimer.h"

CTimer::CTimer(void) :
	g_dwLastFPS(0), g_nFPS(0), g_nFrames(0), m_timeOfLastCall(0),
			m_startTime(0), m_stopTime(0) {
	//initialize the timer
	SDL_Init(SDL_INIT_TIMER);
}

CTimer::~CTimer(void) {
   #ifdef DEBUG
    CLogger::Instance()->log(LOG_LEVEL_NOTICE,"CTimer::~CTimer : Timer deleted");
#endif
}

void CTimer::Start() {
	bool running = true;
	bool paused = false;
	m_startTime = SDL_GetTicks();
}

void CTimer::Stop() {
	bool running = false;
	bool paused = false;
	m_stopTime = SDL_GetTicks();

}

void CTimer::Pause() {
	bool running = false;
	bool paused = true;
	m_stopTime = SDL_GetTicks();
}

void CTimer::Resume() {
	bool running = true;
	bool paused = false;
	m_startTime = m_stopTime;
}

Uint32 CTimer::TimeSinceCreation() {
	return SDL_GetTicks();
}

Uint32 CTimer::TimeSinceEvent() {
	Uint32 thisTime = TimeSinceCreation();
	Uint32 deltaTime = thisTime - m_timeOfLastCall;
	m_timeOfLastCall = thisTime;

	return deltaTime;
}

void CTimer::KeepFPS(const Uint32 fps) {
	if (SDL_GetTicks() - m_startTime <= 1000 / fps) {
		SDL_Delay((1000 / fps) - (SDL_GetTicks() - m_startTime));
	}
}

void CTimer::DrawFPS() {
	//function to draw fps speed to top of the window
	if (SDL_GetTicks() - g_dwLastFPS >= 1000) // When A Second Has Passed...
	{
		g_dwLastFPS = SDL_GetTicks(); // Update Our Time Variable
		g_nFPS = g_nFrames; // Save The FPS
		g_nFrames = 0; // Reset The FPS Counter

		char szTitle[256] = { 0 }; // Build The Title String
		sprintf(szTitle, "Running at: %d FPS", g_nFPS);
		SDL_WM_SetCaption(szTitle, 0);
	}
	g_nFrames++;
}

